import { getCuesSubmitPage, searchTreeOrganization, submitAnalysis } from '@/services/api/api-cues-submit';
import { findTagColor } from '@/utils/findTagColor';
import { FileImageOutlined, PaperClipOutlined } from '@ant-design/icons';
import { LightFilter, ProCard, ProFormCascader, ProFormDateRangePicker} from '@ant-design/pro-components';
import ProTable, { ActionType } from '@ant-design/pro-table';
import { Cascader, Input, Space, Spin, Tag } from 'antd';
import moment from 'moment';
import RcResizeObserver from 'rc-resize-observer';
import React, { useEffect, useRef, useState } from 'react';
import { useAccess } from 'umi';
import DetailsSubmit from './components/DetailsSubmit';
import EditSubmit from './components/EditSubmit';
import style from './TableSubmit.less'
import ReceiptSubmit from './components/ReceiptSubmit';
import ProList from '@ant-design/pro-list';
interface TableTopicSubmitProps {
  isEditable: boolean;
}

const TableSubmit: React.FC<TableTopicSubmitProps> = (props) => {
  const { isEditable } = props;
  const access = useAccess();
  const [loading, setLoadingState] = useState(true);
  const [responsive, setResponsive] = useState(false);
  const [totalData, setTotalDataState] = useState<CuesSubmitData.Analysis>();
  const [width, setWidth] = useState(500);

  const actionRef = useRef<ActionType>();

  const [articleOrganizations, setArticleOrganizationState] = useState<any[]>([]);


  /**
  * 加载 单位 列表
  * @param key
  */
  const analysisData = async () => {
    try {
      const response = await submitAnalysis();
      if (response.code === 0) {
        console.log(response.data);
        setLoadingState(false)
        setTotalDataState(response.data);
      }
    } catch (error) { }
  };
  /**
   * 加载 单位 列表
   * @param key
   */
  const treeOrganizationData = async () => {
    try {
      const response = await searchTreeOrganization();
      if (response.code === 0) {
        setArticleOrganizationState(response.data);
      }
    } catch (error) { }
  };

  /**
   * 搜索参数
   */
  const [queryParam, setQueryParamState] = useState({});

  useEffect(() => {
    treeOrganizationData();
    analysisData();
  }, []);

  const filter = (inputValue: string, path) =>
    path.some(
      (option) => (option.label as string).toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
    );

  return (
    <div>
      {/* {!access.线索征集x配置x提供者 && <Spin spinning={loading} size="large">
        <ProCard
          headerBordered={false}
          bordered={false}
          ghost
          direction={responsive ? 'column' : 'row'}
          style={{marginBottom:15}}
        >
          <ProCard
            headerBordered={false}
            bordered={false}
            className={style.topic}
            split={responsive ? 'horizontal' : 'vertical'}
            style={{ padding: '10px 40px', width: '95%' }}
          >
            {access.线索征集x配置x媒体需求者 && <div>
              <h3>线索报送总量</h3>
              <h2 style={{ color: '#467BE3' }}>{totalData?.countCountySubmit} </h2>
            </div>}
            {access.线索征集x配置x管理员 && <div>
              <h3>线索报送总量</h3>
              <div style={{ display: 'flex' }}>
                <ProCard
                  bordered={false}
                  split={responsive ? 'horizontal' : 'vertical'}
                  style={{ padding: '10px 40px', width: '90%' }}
                >
                  <span>市级部门</span>
                  <h2 style={{ color: '#467BE3' }}>{totalData?.countMunicipalSubmit}</h2>
                </ProCard>
                <ProCard
                  bordered={false}
                  split={responsive ? 'horizontal' : 'vertical'}
                  style={{ padding: '10px 40px', width: '90%', marginLeft: 10 }}
                >
                  <span>区县部门</span>
                  <h2 style={{ color: '#467BE3' }}>{totalData?.countCountySubmit}</h2>
                </ProCard>
              </div>
            </div>}
          </ProCard>
          <ProCard
            bordered={false}
            className={style.submit}
            split={responsive ? 'horizontal' : 'vertical'}
            style={{ padding: '10px 40px', width: '95%' }}
          >
            {access.线索征集x配置x媒体需求者 && <div>
              <h3>报送单位总量</h3>
              <h2 style={{ color: '#467BE3' }}>{totalData?.countMunicipalOrganization} </h2>
            </div>}
            {access.线索征集x配置x管理员 && <div>
              <h3>报送单位总量</h3>
              <div style={{ display: 'flex' }}>
                <ProCard
                  bordered={false}
                  split={responsive ? 'horizontal' : 'vertical'}
                  style={{ padding: '10px 40px', width: '90%' }}
                >
                  <span>市级部门</span>
                  <h2 style={{ color: '#467BE3' }}>{totalData?.countCountyOrganization}</h2>
                </ProCard>
                <ProCard
                  bordered={false}
                  split={responsive ? 'horizontal' : 'vertical'}
                  style={{ padding: '10px 40px', width: '90%', marginLeft: 10 }}
                >
                  <span>区县部门</span>
                  <h2 style={{ color: '#467BE3' }}>{totalData?.countMunicipalOrganization}</h2>
                </ProCard>
              </div>
            </div>}
          </ProCard>
          <ProCard
            bordered={false}
            className={style.active}
            split={responsive ? 'horizontal' : 'vertical'}
            style={{ padding: '10px 40px', width: '95%' }}
          >
            <h3>7天报送分析</h3>
            <TinyArea
              style={{ height: 100 }}
              autoFit={true}
              smooth
              areaStyle={{
                fill: 'l(270) 0:rgb(151 95 228 / 10%) 0.5:rgb(151 95 228 / 60%) 1:rgb(151 95 228)',
              }}
              line={{
                color: '#975FE4',
              }}
              tooltip={{
                customContent: (x, data) => {
                  if (x != null) {
                    return `${totalData?.cuesAnalysisLabelSos[x]?.label}: ${data[0].value}`;
                  } else {
                    return '';
                  }
                },
              }}
              data={totalData ? totalData?.cuesAnalysisLabelSos.map((item) => item.value) : []}
            // data={[0, 0, 0, 0, 31]}
            />
          </ProCard>
        </ProCard>
      </Spin>} */}
      {/* <ProTable<CuesSubmitData.SubmitPage>
        columns={[
          {
            title: '报送线索',
            dataIndex: 'articleName',
            // copyable: true,
            search: false,
            ellipsis: true,
            width: '300px',
            align: 'center',
            key: 'articleName',
            render: (dom, record, _index, action) => {
              return (
                <div
                  style={{
                    textAlign: 'left',
                    textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap',
                    overflow: 'hidden',
                  }}
                >
                  {record.isImage === 1 ? <FileImageOutlined /> : <></>}
                  {record.isFile === 1 ? <PaperClipOutlined /> : <></>}
                  <DetailsSubmit
                    id={record.id}
                    name={record.articleName}
                    onRefurbish={() => {
                      actionRef.current?.reload();
                    }}
                  />
                </div>
              );
            },
          },
          {
            title: '行业',
            dataIndex: 'articleIndustryName',
            key: 'articleIndustryName',
            width: '80px',
            align: 'center',
            search: false,
            render: (_, row) => {
              let industrys = row?.articleIndustrys;

              if (industrys.length > 2) {
                industrys = industrys.slice(0, 2);
                industrys.push({
                  label: '...',
                  value: '...',
                });
              }

              return (
                <Space size={[0, 8]} wrap >
                  {industrys?.map(
                    (item) =>
                      <Tag key={item.value}>{item.label}</Tag>
                    // <div >{item.label}</div>,
                  )}
                </Space>
              );
            },
          },
          {
            title: '单位',
            key: 'articleOrganizationAvatar',
            dataIndex: 'articleOrganizationAvatar',
            width: '180px',
            search: false,
            align: 'center',
            valueType: 'avatar',
            render: (dom, row) => (
              <div
                style={{
                  textAlign: 'left',
                  marginLeft: '16px',
                }}
              >
                <Tag color={findTagColor(row.articleOrganizationTopName)}>
                  {row.articleOrganizationTopName}
                </Tag>
                <span>{dom}</span>
                {row.articleOrganizationName}
              </div>
            ),
          },
          {
            title: '新闻联络人',
            dataIndex: 'articleAccountName',
            // copyable: true,
            ellipsis: true,
            search: false,
            width: '100px',
            align: 'center',
            key: 'articleAccountName',
          },
          // {
          //   title: '阅读情况',
          //   hideInSearch: true,
          //   hideInTable: !access.线索征集x配置x管理员,
          //   dataIndex: 'receipt',
          //   key: 'receipt',
          //   valueType: 'avatar',
          //   width: '80px',
          //   align: 'center',
          //   search: false,
          //   render: (dom, record) => {
          //     return <ReceiptSubmit id={record.id} receipt={'123'} />;
          //   },
          // },
          {
            title: '创建时间',
            dataIndex: 'createdTime',
            key: 'createdTime',
            width: '120px',
            align: 'center',
            search: false,
          },
          {
            title: '操作',
            key: 'option',
            width: 50,
            valueType: 'option',
            hideInTable: !isEditable,
            render: (dom, record, _index, action) => {
              return <EditSubmit
                id={record.id}
                onRefurbish={() => {
                  actionRef.current?.reload();
                }} />
            },
          },
        ]}
        actionRef={actionRef}
        request={async (params = {}) => {
          // if (params.organizationIds) {
          //   const organizationParentIds: string[] = [];
          //   let organizationIds: string[] = [];

          //   params.organizationIds.forEach((item: string | any[]) => {
          //     if (item.length === 1) {
          //       organizationParentIds.push(item[0]);
          //     } else if (item.length > 1) {
          //       organizationIds.push(item[1]);
          //     }
          //   });
          //   organizationParentIds.forEach((id) => {
          //     const ids = articleOrganizations.find((item) => item.id === id).children;
          //     organizationIds = organizationIds.concat(ids.map((item: any) => item.id));
          //   });
          //   params.articleOrganizationIds = organizationIds;
          // }

          const response = await getCuesSubmitPage({
            mode: 1,
            createdSource: 1,
            ...queryParam,
            ...params,
          });

          return Promise.resolve({
            data: response.data.data,
            total: response.data.total,
            success: response.code === 0,
          });
        }}
        rowKey="id"
        dateFormatter="string"
        bordered
        search={false}
        sticky
        ghost
        pagination={{
          showQuickJumper: true,
          showSizeChanger: true,
          defaultPageSize: 20,
        }}
        headerTitle={
          <div
            style={{
              display: 'flex',
            }}
          >
            <Input.Search
              placeholder="查询标题"
              enterButton="搜索"
              allowClear
              style={{ maxWidth: 522, width: '100%' }}
              onChange={(e) => {
                setQueryParamState({ ...queryParam, articleName: e.target.value });
              }}
              onSearch={(value) => {
                actionRef.current?.reset();
              }}
            />

            <ProFormCascader
              width="xl"
              name="articleOrganizationIds"
              placeholder="选择单位"
              formItemProps={{
                style: {
                  width: width - 700,
                  marginLeft: '18px',
                  marginBottom: '0px',
                },
              }}
              fieldProps={{
                options: articleOrganizations,
                showSearch: { filter },
                multiple: true,
                removeIcon: true,
                allowClear: true,
                maxTagCount: 'responsive',
                showCheckedStrategy: Cascader.SHOW_CHILD,
                onChange(value, selectOptions) {
                  setQueryParamState({ ...queryParam, articleOrganizationIds: value });
                  actionRef.current?.reset();
                },
              }}
            />
          </div>
        }
        toolbar={{
          style: {
            marginTop: '-16px',
          },
          filter: (
            <LightFilter
              onValuesChange={(value) => {
                setQueryParamState(value);
                actionRef.current?.reset();
              }}
            >
              <ProFormDateRangePicker
                name="createdTimes"
                label="创建日期"
                allowClear
                fieldProps={{
                  allowClear: true,
                  placeholder: ['开始日期', '结束日期'],
                  format: 'YYYY-MM-DD',
                  ranges: {
                    今日: [moment(), moment()],
                    本月: [moment().startOf('month'), moment().endOf('month')],
                    上月: [
                      moment().startOf('month').subtract(1, 'months'),
                      moment().endOf('month').subtract(1, 'months'),
                    ],
                    最近7天: [moment().subtract(6, 'days'), moment()],
                    最近60天: [moment().subtract(59, 'days'), moment()],
                    最近90天: [moment().subtract(89, 'days'), moment()],
                  },
                }}
              />
            </LightFilter>
          ),
        }}
      /> */}
      <Input.Search
        placeholder="查询标题"
        enterButton="搜索"
        allowClear
        style={{ maxWidth: 522, width: '100%' }}
        onChange={(e) => {
          setQueryParamState({ ...queryParam, articleName: e.target.value });
        }}
        onSearch={(value) => {
          actionRef.current?.reset();
        }}
      />
      <ProList<CuesSubmitData.SubmitPage>
        header={false}
        actionRef={actionRef}
        request={async (params = {}) => {
          const response = await getCuesSubmitPage({
            mode: 1,
            createdSource: 1,
            ...queryParam,
            ...params,
          });

          return Promise.resolve({
            data: response.data.data,
            total: response.data.total,
            success: response.code === 0,
          });
        }}
        pagination={{
          defaultPageSize: 8,
          showSizeChanger: false,
          showTotal: false,
          style: { textAlign: 'center' },
        }}
        showActions="hover"
        grid={{ gutter: 18, column: 1 }}
        onItem={(record: any) => {
          return {
            onMouseEnter: () => { },
            onClick: () => { },
          };
        }}
        renderItem={(item: CuesSubmitData.SubmitPage, index: number) => {
          return (
            <DetailsSubmit
              item={item}
              id={item.id}
              onRefurbish={() => {
                actionRef.current?.reload();
              }}
              triggerMode="card"
              name={item.articleName}
            />
          );
        }}
        rowKey={'id'}
        toolBarRender={false}
        style={{ marginTop: 10 }}
      />
    </div>
  );
};

export default TableSubmit;
